﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FindPath : MonoBehaviour
{
    public float moveSpeed=15f;
    public Transform[] wayPoints;//路径点数组
    public int wp_index;//路径点序号
    public float timer;
    void Start()
    {
        //查找路径点父物体
        Transform pathA = GameObject.Find("Path").transform;
        if (pathA != null)
        {
            //根据子物体数量来给数组申请内存
            if (pathA.childCount != 0)
                wayPoints = new Transform[pathA.childCount];
        }
        //将路径点加到数组中
        for (int i = 0; i < wayPoints.Length; i++)
        {
            wayPoints[i] = pathA.GetChild(i);
        }
    }

    // Update is called once per frame
    void Update()
    {
        //确定目标方向
        Vector3 direction = wayPoints[wp_index].position - transform.position;
        //transform.LookAt(direction);
        //球形插值旋转
        transform.rotation = Quaternion.Slerp(transform.rotation,
                                        Quaternion.LookRotation(direction),
                                        0.01f);
        timer+=Time.deltaTime;
        if (timer>=5)
        {
            //切换到下一个随机目标点
                wp_index = Random.Range(0,wayPoints.Length);//Unity中随机函数为Random.Range(a,b),取a，b之间的一个数字
        }
        transform.Translate(Vector3.forward * Time.deltaTime * moveSpeed);
    }
}
